package com.platform.controller;

import com.alibaba.fastjson.JSONException;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.platform.entity.SmsHistoryEntity;
import com.platform.entity.UserEntity;
import com.platform.service.SmsHistoryService;
import com.platform.service.UserService;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2018-10-21 00:36:13
 */
@RestController
@RequestMapping("smshistory")
public class SmsHistoryController {
    @Autowired
    private SmsHistoryService smsHistoryService;

    @Autowired
    private UserService userService;

    // 短信应用SDK AppID
    private static int appid = 1400056656; // 1400开头

    // 短信应用SDK AppKey
    private static String appkey = "fb6e46e9a9e037b4d241391805cf6aad";

    // 需要发送短信的手机号码
    //private static String[] phoneNumbers = {"21212313123", "12345678902", "12345678903"};

    // 短信模板ID，需要在短信应用中申请
    //private static int templateId = 74479; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
    //templateId7839对应的内容是"您的验证码是: {1}"
    // 签名
    private static String smsSign = "众蜜空间"; // NOTE: 这里的签名"腾讯云"只是一个示例，真实的签名需要在短信控制台中申请，另外签名参数使用的是`签名内容`，而不是`签名ID`

    public static SmsMultiSenderResult tencentSendSms(int templateId, String[] phoneNumbers, String[] params) throws Exception {
        SmsMultiSenderResult result = null;
        try {

            SmsMultiSender msender = new SmsMultiSender(appid, appkey);
            result = msender.sendWithParam("86", phoneNumbers,
                    templateId, params, smsSign, "", "");
            System.out.println(result);
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("smshistory:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<SmsHistoryEntity> smsHistoryList = smsHistoryService.queryList(query);
        int total = smsHistoryService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(smsHistoryList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("smshistory:info")
    public R info(@PathVariable("id") Integer id) {
        SmsHistoryEntity smsHistory = smsHistoryService.queryObject(id);

        return R.ok().put("smsHistory", smsHistory);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("smshistory:save")
    public R save(@RequestBody SmsHistoryEntity smsHistory) {

        String phone = "";

        String[] prems = new String[]{
                ""};


        ArrayList<String> list = new ArrayList<>();

        String[] phones;
        if (smsHistory.getSendrange() == 1) {
            phones = smsHistory.getTophones().split("-");
        } else {
            Map<String, Object> param = new HashMap<String, Object>();
            List<UserEntity> userList = userService.queryList(param);
            if (userList.size() > 0) {
                for (UserEntity userEntity : userList) {
                    list.add(userEntity.getMobile());
                }
            }
            phones = (String[]) list.toArray();
        }



        /*prems.add("5");//5分钟*/
        SmsMultiSenderResult smsresult = null;
        try {
            smsresult = tencentSendSms(smsHistory.getTemplateid(), phones, prems);
        } catch (Exception e) {
            return R.error(e.getMessage());
            //return R.error();
        }
        if (smsresult.errMsg.equals("OK")) {
            smsHistoryService.save(smsHistory);
            return R.ok();

        } else
            return R.error(smsresult.errMsg);

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("smshistory:update")
    public R update(@RequestBody SmsHistoryEntity smsHistory) {
        smsHistoryService.update(smsHistory);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("smshistory:delete")
    public R delete(@RequestBody Integer[] ids) {
        smsHistoryService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<SmsHistoryEntity> list = smsHistoryService.queryList(params);

        return R.ok().put("list", list);
    }
}
